--
-- Author: yawei.zhu
-- Date: 2018-12-14 17:51:15
--
-- PvpChallengePanel
--
local IconRender = require("app.widget.renders.IconRender")
local AvatarFactory = require("app.public.avatar.AvatarFactory")
local NewTeamMemberPanel = require("app.team.views.NewTeamMemberPanel")
local PvpChallengeLeftPanel = import(".PvpChallengeLeftPanel")

local ClassRef = app.mvc.createPanelClass(...)

local arrKey = {"victoryReward", "goldCupReward", "silverCupReward", "copperCupReward", "failureReward"}
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.PvpChallengeNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    
    self._challengeLeft = PvpChallengeLeftPanel.create(self._ui.left)
    self._challengeLeft:onOperate(function(op, data)
        executeFunc(self._onOperate, op, data)
    end)

    -- 顶部
    self._topPanel = self._ui.Panel_top
    local rankBtn = self._topPanel:findChild("Panel_bg/rank_btn")
    rankBtn:addClickEventListener(function()
        local challengeConf = GD:getChallengeInfo(self._challengeInfo.playId)
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK, mode = "open", rankingId = tonumber(challengeConf.rankId)})
    end)

    -- 底部
    self._bomPanel = self._ui.Panel_bom
    local bomPanel = self._bomPanel
    self._createBtn = bomPanel:getChildByName("Button_enter")
    self._createBtnName = self._createBtn:getChildByName("name")
    self._bomText = bomPanel:getChildByName("Text")
    self._singleBtn = bomPanel:getChildByName("Button_found")
    self._singleRightBtn = bomPanel:getChildByName("Button_one")
    self._challengeTips = bomPanel:getChildByName("icon_text")

    self._singleBtn:addClickEventListener(function()
        if not self._isTimeOpen then
            display.pushToast(L("ErrEventNotStart"))
            return 
        end
        if self.allFlag then
            local confirmDialog = display.newConfirmDialog( L("challengeTips21"), function()
                executeFunc(self._onOperate, "PvpChallenge_match")
            end)
            UIHandler:addPopDialog(confirmDialog)
        else
            executeFunc(self._onOperate, "PvpChallenge_match")
        end
    end)

    self._singleRightBtn:addClickEventListener(function()
        if not self._isTimeOpen then
            display.pushToast(L("ErrEventNotStart"))
            return 
        end
        if self.allFlag then
            local confirmDialog = display.newConfirmDialog( L("challengeTips21"), function()
                executeFunc(self._onOperate, "PvpChallenge_match")
            end)
            UIHandler:addPopDialog(confirmDialog)
        else
            executeFunc(self._onOperate, "PvpChallenge_match")
        end
    end)

    self._createBtn:addClickEventListener(function() -- 创建队伍/匹配/取消匹配 按钮响应
        if not self._isTimeOpen then
            display.pushToast(L("ErrEventNotStart"))
            return 
        end

        if L("champion_team7") == self._createBtnName:getString() then
            executeFunc(self._onOperate, "PvpChallenge_createTeam" )
        elseif L("lua_code_text_102") == self._createBtnName:getString() then
            if self._isLeader then
                -- executeFunc(self._onOperate, "PvpChallenge_match")
                if self.allFlag then
                    local confirmDialog = display.newConfirmDialog( L("challengeTips21"), function()
                        executeFunc(self._onOperate, "reqTeamMatchChallenge")
                    end)
                    UIHandler:addPopDialog(confirmDialog)
                else
                    executeFunc(self._onOperate, "reqTeamMatchChallenge")
                end
            else
                local dlg = display.newConfirmDialog( L("team_text6"),
                    function() -- 确定
                        app:sendMsg("TeamModel", "reqQuitTeam")
                    end)
                UIHandler:addPopDialog( dlg )
            end
        elseif L("lua_code_text_110") == self._createBtnName:getString() then
            executeFunc(self._onOperate, "PvpChallenge_cancelMatch")
        end
    end)

    local searchNode = bomPanel:getChildByName("Button_tips")
    searchNode:getChildByName("Panel_1"):addClickEventListener(function()
        dump(self._challengeInfo.playId)
        executeFunc(self._onOperate, "PvpChallenge_search", self._challengeInfo.playId)
    end)    

    local iconPanel = bomPanel:getChildByName("Panel_icon")
    self._iconRenders = {}
    self._iconText = {}
    for i = 1, 5 do
        local render = IconRender.create(iconPanel:getChildByName("icon"..i))
        render:setTipEnable(true)
        self._iconRenders[i] = render
        self._iconText[i] = iconPanel:getChildByName("Text_"..i)
    end

    -- 队伍相关
    self._teamPanel = self._ui.Panel_team
    self._teamMemberPanel = NewTeamMemberPanel.create(self._teamPanel:getChildByName("player"))
    self._teamData = self._teamPanel:getChildByName("Panel_data")
    self._oneVone = self._teamPanel:getChildByName("1v1")
    self._oneVone:setVisible(false)

    self._teamMemberPanel:registerOnOperate(function(op)
        executeFunc(self._onOperate, op)
    end)

    -- 按钮相关
    local dataPanel = self._teamData
    self._btnApply = dataPanel:getChildByName("Button_apply")
    self._applyDot = self._btnApply:getChildByName("dotNew")
    self._btnLeave = dataPanel:getChildByName("Button_leave")
    self._btnSet = dataPanel:getChildByName("Button_set")
    self._panelNum = dataPanel:getChildByName("Panel_num")
    self._totalPow = self._panelNum:getChildByName("combat_num")
    self._powDesc = self._panelNum:getChildByName("combat_tlt")
    self._powDesc:setString( L("champion_team8") )

    self._btnApply:addClickEventListener(function() -- 展开申请列表
        executeFunc(self._onOperate, "PvpChallenge_showApplyList")
        self:refreshNewApplyerFlag( false )
    end)
    self._btnLeave:addClickEventListener(function() -- 退出队伍
        local creataeTeamDialog = display.newConfirmDialog( L("champion_team9"),
            function() -- 确定
                executeFunc(self._onOperate, "PvpChallenge_quitTeam")
            end)
        UIHandler:addPopDialog( creataeTeamDialog )
    end)
    self._btnSet:addClickEventListener(function() -- 打开己方队伍设置
        executeFunc(self._onOperate, "PvpChallenge_TeamSettingUI", { 2 } ) -- "我"的设置
    end)

    -- 开启时间
    self._tipsTime = self._topPanel:getChildByName("tips_time")
    self._textTime = self._tipsTime:getChildByName("text")

    local szTimes = string.split(GD:getSystemStrPar("challengeGameTime"), "|")
    self._openTimes = {}
    for i, strTime in ipairs(szTimes) do
        local startHour, startMin, endHour, endMin = string.match(strTime, "(%d+):(%d+)-(%d+):(%d+)")
        local value = {}
        value.startTime = startHour * 3600 + startMin * 60
        value.endTime = endHour * 3600 + endMin * 60
        self._openTimes[i] = value
    end

    -- 匹配
    -- 裁切搜索动画
    local searchPanel = self._ui.Panel_pipei
    local aniPanel = searchPanel:getChildByName("Panel_ani")
    local di = aniPanel:getChildByName("di")
    di:retain()
    di:removeFromParent()

    local mask = aniPanel:getChildByName("mask")
    mask:retain()
    mask:removeFromParent()

    local cilpNode = cc.ClippingNode:create()
    cilpNode:setAlphaThreshold(0.5)
    cilpNode:setPosition(0, 0)
    cilpNode:addChild(di)
    cilpNode:setStencil(mask)
    cilpNode:addTo(aniPanel, -1)

    di:release()
    mask:release()
end

function ClassRef:_tick(dt)
    function calcTime()
        self._isTimeOpen = false
        local serverDate = app.session:getServerDate()
        local todayTime = serverDate.hour * 3600 + serverDate.min * 60 + serverDate.sec
        for _, date in ipairs(self._openTimes) do
            if todayTime < date.startTime then
                self._remainedTime = date.startTime - todayTime
                self._isTimeOpen = false
                break
            elseif todayTime >= date.startTime and todayTime < date.endTime then
                self._remainedTime = date.endTime - todayTime
                self._isTimeOpen = true
                break
            end
        end

        -- 过了今天的开启时间了
        if todayTime >= self._openTimes[#self._openTimes].endTime then
            self._remainedTime = self._openTimes[1].startTime + 24 * 3600 - todayTime
            self._isTimeOpen = false
        end

        dump(todayTime)
        dump(self._openTimes)
    end

    if not self._remainedTime or self._remainedTime <= 0 then 
        calcTime()
    end
    self._remainedTime = self._remainedTime - 1
    local str = self._isTimeOpen and L("lua_code_text_108") or L("lua_code_text_154")
    local _, timeStr = TimeUtil.secondsToStr(self._remainedTime, 1)
    self._textTime:setString(string.format(str, timeStr))
end

function ClassRef:updateView(challengeInfo, isNewApplyerFlag)
    self._challengeInfo = challengeInfo
    self._challengeLeft:updateInfo(challengeInfo)
    -- 更新top
    local targetConf = GD:queryTeamTargetById(challengeInfo.playId)
    local iconPath = string.format(Res.TeamTargetPath, targetConf.iconPath)
    self._topPanel:getChildByName("icon"):loadTexture(iconPath)
    self._topPanel:getChildByName("name"):setString(string.format(L("challengeTips8"), L(targetConf.name)))
    self._topPanel:getChildByName("desc"):setString(L(targetConf.desc))
    self._maxNum = tonumber(targetConf.maxNum)
    -- 注册定时器
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
    self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
    self:_tick()

    -- 底部奖励
    local challengeConf = GD:getChallengeInfo(challengeInfo.playId)
    local rankId = tonumber(challengeConf.rankId)
    local rankInfo = GD:getRankingConfigById(rankId)
    local myRank = challengeInfo.myRank
    if challengeInfo.winTimes <= 0 or myRank <= 0 or myRank > tonumber(rankInfo.limit) then
        myRank = L("bossRank_notOnTheList")
    end
    self._topPanel:getChildByName("num_text"):setString(string.format(L(challengeConf.rankShow), challengeInfo.winTimes, myRank))

    local intervalX = 58
    local posX = 5
    local count = 0
    for i = 1, 5 do
        local render = self._iconRenders[i]
        local text = self._iconText[i]
        local value = challengeConf[arrKey[i]]
        if value then
            count = count + 1
            render:setVisible(true)
            text:setVisible(true)
            local reward = UD:parseRewardToBagItem(value)
            render:setData(reward)
            local renderX = posX + (count - 1) * intervalX
            render:setPositionX(renderX)
            text:setPositionX(renderX + 29)
        else            
            render:setVisible(false)
            text:setVisible(false)
        end
    end

    -- 挑战赛星章数上限，胜场数上限
	local maxWinTimes = tonumber(challengeConf.winNumMax)
	local maxScore = tonumber( GD:getSystemPar( "challengeGameMaxDailyBadge", 100) )
	self.allFlag = (challengeInfo.dailyScore >= maxScore and challengeInfo.winTimes >= maxWinTimes) or false
	self.starCountFlag = challengeInfo.dailyScore >= maxScore or false
	if self.allFlag then
		self._challengeTips:findChild("Panel/Text"):setString(L("challengeTips20"))
	elseif self.starCountFlag then
		self._challengeTips:findChild("Panel/Text"):setString(L("challengeTips19"))
	end
	self._challengeTips:setVisible(self.allFlag or self.starCountFlag)
	self._bomPanel:getChildByName("Panel_icon"):setVisible(not (self.allFlag or self.starCountFlag))
    
    self._ui.Panel_team:setVisible(false)
    self._ui.Panel_pipei:setVisible(false)
    self._ui.Panel_no:setVisible(false)

    self._singleBtn:setVisible(false)
    self._singleRightBtn:setVisible(false)
    self._createBtn:setVisible(false)
    display.setBtnTouchEnable(self._createBtn, true)

    -- 未匹配
    if challengeInfo:getState() == "idle" then
        executeFunc(self._onOperate, "refreshChallengeMemberList") 
    else
        -- 匹配中
        self._ui.Panel_pipei:setVisible(true)
        self._createBtn:setVisible(true)
        self._createBtnName:setString(L("lua_code_text_110"))

        local teammates = challengeInfo:getTeammates()
        local count = #teammates -- 暂时不考虑大于3的情况
        local midX = 365
        local intervalX = 90
        local midNum = (count + 1) / 2
        for i = 1, 3 do
            local icon = self._ui.Panel_pipei:getChildByName("icon_"..i)
            local img = icon:getChildByName("icon_img")
            img:setVisible(false)
            if i <= count then 
                icon:setVisible(true)
                icon:setPositionX(midX - (midNum - i) * intervalX)

                AvatarFactory.getOrCreateHeroIconPath(teammates[i], function(path)
                    if not cc.isDead(self) then
                        img:loadTexture(path)
                        img:setVisible(true)
                    end
                end)

            else
                icon:setVisible(false)
            end
        end

        -- 备战中
        if challengeInfo:getState() == "prepare" then
            self._ui["Panel/Panel_pipei/text"]:setString(L("challengeTips6"))
            display.setBtnTouchEnable(self._createBtn, false)
        end
    end 
end

function ClassRef:refreshTeamMemberList(team, isNewApplyerFlag)
    -- 未匹配状态
    if self._challengeInfo:getState() ~= "idle" then return end

    self._ui.Panel_team:setVisible(false)
    self._ui.Panel_no:setVisible(false)
    self._singleBtn:setVisible(false)
    self._singleRightBtn:setVisible(false)
    self._createBtn:setVisible(false)

    if team and team:isInTeam(UD.player.uid) then
        -- 有队伍
        self._ui.Panel_team:setVisible(true)
        self._teamMemberPanel:setVisible(true)
        self._teamData:setVisible(true) 

        self._teamMemberPanel:setData(team)

        -- 玩法最大人数
        local maxNum = self._maxNum
        -- 刷新超限制人数禁止标志
        self._teamMemberPanel:refreshForbiddenIconStatus(maxNum)

        -- 队伍真实玩家的战斗力
        local teamCombatPower = team:getTeamTotalCapacity()
        self._totalPow:setString(teamCombatPower)
        -- 居中对齐
        display.setNodesMiddle(self._panelNum, nil, self._powDesc, self._totalPow)
        
        self:refreshNewApplyerFlag(isNewApplyerFlag)
    
        self._isLeader = team:isLeader(UD.player.uid)
        self:updateTeamBtn(self._isLeader)
    else
        -- 无队伍
        self._ui.Panel_no:setVisible(true)
    end

    -- 设置匹配按钮状态
    if self._maxNum == 1 then -- 1v1的玩法 只显示单人匹配
        self._singleRightBtn:setVisible(true)
    else
        if team and team:isInTeam(UD.player.uid) then
            self._createBtn:setVisible(true)
            self._createBtnName:setString(L("lua_code_text_102"))
        else
            self._createBtn:setVisible(true)
            self._singleBtn:setVisible(true)
            self._createBtnName:setString(L("champion_team7"))
        end
    end
end

-- 刷新新申请者new标记状态
function ClassRef:refreshNewApplyerFlag(visible)
    self._applyDot:setVisible(visible)
end

-- 更新队伍按钮状态
function ClassRef:updateTeamBtn(isLeader)
    if isLeader then
        self._btnApply:setVisible(true)
    else
        self._btnApply:setVisible(false)
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

function ClassRef:onExit()
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
end

return ClassRef
